//
//  OverlayAnimationController.m
//  UIViewControllerTransitionDemo
//
//  Created by Guo Rui on 2017/7/6.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "OverlayAnimationController.h"

@implementation OverlayAnimationController

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return .5f;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    UIViewController *fromVc = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVc = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *containerView = [transitionContext containerView];
    
    if (toVc.isBeingPresented) {
        [containerView addSubview:toVc.view];
        
        CGRect toFinalFrame = [transitionContext finalFrameForViewController:toVc];
        
        CGRect toInitialFrame = toFinalFrame;
        toInitialFrame.size.width = 0.f;
        
        toVc.view.bounds = (CGRect){CGPointZero, toInitialFrame.size};
        toVc.view.center = containerView.center;
        
        [UIView animateWithDuration:[self transitionDuration:transitionContext]
                         animations:^{
                             toVc.view.bounds = (CGRect){CGPointZero, toFinalFrame.size};
                         } completion:^(BOOL finished) {
                             [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
                         }];
    }
    
    if (fromVc.isBeingDismissed) {
        
        CGRect fromInitialFrame = [transitionContext initialFrameForViewController:fromVc];
        CGRect fromFinalFrame = fromInitialFrame;
        fromFinalFrame.size.width = 0;
        
        [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
            fromVc.view.bounds = (CGRect){CGPointZero, fromFinalFrame.size};
        } completion:^(BOOL finished) {
            [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
        }];
    }
}


@end
